package com.lenovo.newsapp.activity;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.adobe.mobile.Analytics;
import com.adobe.mobile.Config;
import com.lenovo.newsapp.R;
import com.lenovo.newsapp.util.ThreadPool;

public class TwitterActivity extends Activity {
	private static final String TAG = "TwitterActivity";

	private static final String PREF_ACCESS_TOKEN = "accessToken";
	private static final String PREF_ACCESS_TOKEN_SECRET = "accessTokenSecret";

	private static final String CONSUMER_KEY = "6XoyMbwZ6mXckaXfZS5xg";
	private static final String CONSUMER_SECRET = "JBjQ4onLeFTmINdxvj3X7CUk9OnxB7NqRBZMUZoE"; // XXX
	private static final String CALLBACK_URL = "https://lenovocentral.lenovo.com";
	private SharedPreferences mPrefs;
	private Twitter mTwitter;
	private RequestToken mReqToken;

	private Button mLoginButton;
	private Button mTweetButton;
	final Handler handler = new Handler();
	private WebView web;
	private EditText et;

	private String title;

	private ProgressBar webpd;
	private boolean success;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_tweet_to_twitter);
		mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE);
		Log.i(TAG, "Got Preferences");
//		title = getIntent().getStringExtra("params");
		title = getIntent().getStringExtra("title") + " " + getIntent().getStringExtra("shareUrl");
		Log.v(TAG, "title--- " + title);
		
		ConfigurationBuilder builder = new ConfigurationBuilder();
		Configuration conf = builder.build();
		mTwitter = new TwitterFactory(conf).getInstance();
		mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);

		mTweetButton = (Button) findViewById(R.id.tweet_button);
		et = (EditText) findViewById(R.id.et);
		et.setText(title);
		web = (WebView) findViewById(R.id.web);
		webpd = (ProgressBar) findViewById(R.id.load_prgressbar);
		et.setVisibility(View.VISIBLE);
		mTweetButton.setVisibility(View.VISIBLE);
		mTweetButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String token = mPrefs.getString(PREF_ACCESS_TOKEN, null);
				String secret = mPrefs
						.getString(PREF_ACCESS_TOKEN_SECRET, null);
				Log.i(TAG, "保存token--" + token);
				Log.i(TAG, "保存secret--" + secret);
				 if(token != null && secret != null){
				 Log.i(TAG, "直接发送推文---");
				 sendTwitter(token,secret);
				 }else{
				Log.i(TAG, "去授权---");
				loginNewUser();
				 }
			}

		});
		
		Analytics.trackState("TwitterActivity", null);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Config.pauseCollectingLifecycleData();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Config.collectLifecycleData();
	}

	private void sendTwitter(final String token, final String secret) {
		webpd.setVisibility(View.VISIBLE);
		ThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				try {

					AccessToken at = new AccessToken(token, secret);

					mTwitter.setOAuthAccessToken(at);
					Log.i(TAG, "开始发送文字---");

					Status status = mTwitter.updateStatus(et.getText()
							.toString());
					Log.i(TAG, "完成---" + status.getText());

						success = true;
				} catch (TwitterException e) {
					success = false;
					Log.i(TAG, "异常---" + e);
					e.printStackTrace();
				}
				handler.post(new Runnable() {

					@Override
					public void run() {

						webpd.setVisibility(View.GONE);
						if (success) {
							Toast.makeText(TwitterActivity.this, "success",
									Toast.LENGTH_LONG).show();
						} else {
							Toast.makeText(TwitterActivity.this, "failed",
									Toast.LENGTH_LONG).show();
						}

						finish();
					}

				});
			}
		});
	}

	/**
	 * 授权
	 */

	private void loginNewUser() {
		webpd.setVisibility(View.VISIBLE);
		ThreadPool.execute(new Runnable() {

			@Override
			public void run() {

				try {
					Log.i(TAG, "Request App Authentication");

					mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);

					success = true;
					

				} catch (TwitterException e) {
					Log.i(TAG, "e---" + e);
					success = false;
				}

				handler.post(new Runnable() {

					@Override
					public void run() {
						
						Log.i(TAG, "Starting Webview to login to twitter");
						if(success){
						if(mReqToken != null ){
							String url = mReqToken.getAuthenticationURL();
							
							Log.i(TAG, "url--" + url);
							webpd.setVisibility(View.GONE);
							et.setVisibility(View.GONE);
							mTweetButton.setVisibility(View.GONE);
							if(url == null){
								Toast.makeText(TwitterActivity.this, "failed",
										Toast.LENGTH_LONG).show();
								finish();
							}else{
								
								goShowWeb(url);
							}
						}else{
							Toast.makeText(TwitterActivity.this, "failed",
									Toast.LENGTH_LONG).show();
							finish();
						}
						}else{
							Toast.makeText(TwitterActivity.this, "failed",
									Toast.LENGTH_LONG).show();
							finish();
						}
						

					}

				});
			}
		});

	}

	/**
	 * 展示授权页面
	 */
	private void goShowWeb(String url) {

		web.setVisibility(View.VISIBLE);
		web.loadUrl(url);
		web.setWebViewClient(new WebViewClient() {
			private String oauthToken;
			private String oauthVerifier;

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				if (url != null && url.startsWith(CALLBACK_URL)) {
					web.setVisibility(View.GONE);
					String[] param = url.split("\\?")[1].split("&");
					if (param[0].startsWith("oauth_token")) {
						oauthToken = param[0].split("=")[1];
					} else if (param[1].startsWith("oauth_token")) {
						oauthToken = param[1].split("=")[1];
					}
					if (param[0].startsWith("oauth_verifier")) {
						oauthVerifier = param[0].split("=")[1];
					} else if (param[1].startsWith("oauth_verifier")) {
						oauthVerifier = param[1].split("=")[1];
					}
					Log.i(TAG, "oauthVerifier--" + oauthVerifier);
					authoriseNewUser(oauthVerifier);
				}
				;
			}
		});
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		Log.i(TAG, "New Intent Arrived");
	}


	/**
	 * 获取AccessToken
	 * 
	 * @param oauthVerifier
	 */
	private void authoriseNewUser(final String oauthVerifier) {
		Log.i(TAG, "开始获取accesstoken--");
		webpd.setVisibility(View.VISIBLE);
		ThreadPool.execute(new Runnable() {

			private AccessToken at;

			@Override
			public void run() {

				try {
					at = mTwitter.getOAuthAccessToken(mReqToken, oauthVerifier);
					long id = at.getUserId();
					Log.i(TAG, "userid--" + id);
					String token = at.getToken();
					String secret = at.getTokenSecret();
					Log.i(TAG, "token---" + token);
					Log.i(TAG, "secret---" + secret);
					Editor editor = mPrefs.edit();
					editor.putString(PREF_ACCESS_TOKEN, token);
					editor.putString(PREF_ACCESS_TOKEN_SECRET, secret);
					editor.commit();
					Status status = mTwitter.updateStatus(et.getText()
							.toString());
					Log.i(TAG, "授权后直接发送---" + status.getText());
//					saveAccessToken(at);
						success = true;
				} catch (TwitterException e) {
					Log.i(TAG, "e---" + e);
					success = false;
					e.printStackTrace();
				}
				handler.post(new Runnable() {

					@Override
					public void run() {
						webpd.setVisibility(View.VISIBLE);
						Log.i(TAG, "授权后success---" + success);
						if (success) {
							Toast.makeText(TwitterActivity.this, "success",
									Toast.LENGTH_LONG).show();
						} else {
							Toast.makeText(TwitterActivity.this, "sent",
									Toast.LENGTH_LONG).show();
						}
						finish();
					}
				});
			}
		});

	}

	/**
	 * 存储AccessToken
	 * 
	 * @param at
	 */
	private void saveAccessToken(AccessToken at) {
		String token = at.getToken();
		String secret = at.getTokenSecret();
		Log.i(TAG, "token---" + token);
		Log.i(TAG, "secret---" + secret);
		Editor editor = mPrefs.edit();
		editor.putString(PREF_ACCESS_TOKEN, token);
		editor.putString(PREF_ACCESS_TOKEN_SECRET, secret);
		editor.commit();
	}

}
